package main

import (
	"fmt"
	"io"
	"net"
	"os"
)

const (
	DATA_SIZE  = 4096000
	CONN_COUNT = 1
)

var data [DATA_SIZE]byte
var done chan struct{}

func init() {
	for i := 0; i < DATA_SIZE; i++ {
		data[i] = 'c'
	}
	done = make(chan struct{}, CONN_COUNT)
}

func request(id int) {
	var buf [4096]byte
	tcpAddr, _ := net.ResolveTCPAddr("tcp", "localhost:8001")
	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v", err)
		conn.CloseWrite()
		return
	}
	n, err := conn.Write(data[:])
	if err != nil {
		fmt.Fprintf(os.Stderr, "%d %v", n, err)
		conn.CloseWrite()
		return
	}
	conn.CloseWrite()
	var recv []int
	var total int
	for {
		n, err := conn.Read(buf[:])
		//fmt.Printf("id:%d recv:%d\n", id, n)
		total += n
		recv = append(recv, n)

		if err == io.EOF {
			break
		}

		if err != nil {
			fmt.Fprintf(os.Stderr, "%v", err)
			break
		}
	}

	fmt.Printf("client %d close, recv %d bytes, recv\n", id, total)
	done <- struct{}{}
}

func main() {
	for i := 0; i < CONN_COUNT; i++ {
		go request(i)
	}

	for i := 0; i < CONN_COUNT; i++ {
		<-done
		//fmt.Printf("\r%d", i)
	}
}
